<template>
    <!-- 导航栏 -->
    <van-nav-bar
        title="购物车"
        left-text="返回"
        left-arrow
        fixed
        placeholder
        z-index="1000"
        @click-left="OnBack"
    />

    <van-pull-refresh v-model="refreshing" @refresh="OnRefresh">
        <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="OnLoad"
        >
            <van-checkbox-group v-model="CheckedArr" ref="CheckboxGroup" @change="OnToggleGroup">
                <div class="cart" v-for="(item,index) in CartList" :key="item.id">
                    <!-- 滑动单元格 -->
                    <van-swipe-cell>
                        <van-checkbox :name="item.id"></van-checkbox>
                        <!-- 商品卡片 -->
                        <van-card
                            :thumb="item.product.thumb_text"
                            @click-thumb="ToProductInfo(item.product.id)"
                        >
                            <template #title>
                                <div class="title" @click="ToProductInfo(item.product.id)">{{ item.product.name }}</div>
                            </template>

                            <!-- 卡片的插槽部分 -->
                            <template #desc v-if="item.attrs">
                                <van-tag v-for="(attr,index) in item.attrs" :key="index" class="tag" type="primary">{{attr.value}}</van-tag>
                                <van-tag class="tag" type="warning" v-if="item.type === 'live'">直播商品</van-tag>
                            </template>

                            <!-- 卡片的插槽部分 -->
                            <template #desc v-else>
                                <van-tag class="tag" type="danger">无商品规格</van-tag>
                                <van-tag class="tag" type="warning" v-if="item.type === 'live'">直播商品</van-tag>
                            </template>

                            <template #tags>
                                <div class="price">单价：￥{{ item.price }}</div>
                            </template>

                            <template #price>
                                <div class="price">合计：￥{{ item.total }}</div>
                            </template>

                            <!-- 卡片的商品数量 步进器 -->
                            <template #num>
                                <van-stepper v-model="item.nums" disable-input :name="index" :max="item.product.live_stock ? item.product.live_stock : item.product.stock" @change="OnCartUpdate" />
                            </template>
                        </van-card>

                        <!-- 滑动单元格插槽 右侧滑动 -->
                        <template #right>
                            <van-button
                                square
                                text="删除"
                                type="danger"
                                class="delete-button"
                                @click="OnDel(item,index)"
                            />
                        </template>
                    </van-swipe-cell>
                </div>
            </van-checkbox-group>

            <van-back-top :bottom="'80'" />
        </van-list>
    </van-pull-refresh>

    <div style="height: 50px;"></div>

    <!-- 提交动作栏 -->
    <van-submit-bar :price="total" button-text="提交订单" @submit="OnSubmit">
        <van-checkbox v-model="CheckedAll" :indeterminate="IsIndeterminate" @change="OnToggle">全选</van-checkbox>
    </van-submit-bar>
</template>

<script setup>
const { proxy } = getCurrentInstance();

const business = proxy.$business;
const action = ref(proxy.$route.query.action ?? '');

const CartList = ref([]);// 购物车数据
const refreshing = ref(false);
const finished = ref(false);
const loading = ref(false);
const IsIndeterminate = ref(false);
const page = ref(1);
const CheckedArr = ref([]);
const CheckedAll = ref(false);
const CheckboxGroup = ref(null);

// 刷新
const OnRefresh = () =>
{
    refreshing.value = true;
    finished.value = false;
    loading.value = true;
    page.value = 1;
    CartList.value = [];

    setTimeout(OnLoad,1500);
}

// 上拉加载
const OnLoad = async () =>
{
    if(refreshing.value === true)
    {
        refreshing.value = false;
    }

    const params = {
        page:page.value,
        busid:business.value.id
    }
    
    const result = await proxy.$http.post('/cart/index',params);
    
    loading.value = false;

    if(result.code === 1)
    {
        let count = result.data.count;
        CartList.value = CartList.value.concat(result.data.list);

        CartList.value.map(item => item.attrs = JSON.parse(item.attrs));

        if(CartList.value.length >= count)
        {
            finished.value = true;

            return false;
        }

        page.value += 1;
    }else{
        finished.value = true;
        proxy.$fail(result.msg);
    }
}

// 提交订单
const OnSubmit = () =>
{
    if(CheckedArr.value.length <= 0)
    {
        proxy.$fail('请选择结算的商品');

        return false;
    }

    // 由于地址栏只能携带字符串，所以需要把数组转成字符串
    const cartids = CheckedArr.value.join(',');

    proxy.$router.push({path:'/cart/confirm',query:{cartids}});
}

// 
const OnToggleGroup = () =>
{
    CheckedAll.value = CheckedArr.value.length === CartList.value.length;
    IsIndeterminate.value = CheckedArr.value.length > 0 && CheckedArr.value.length < CartList.value.length;
}

// 全选/取消全选
const OnToggle = (value) => CheckboxGroup?.value.toggleAll(value);

const OnCartUpdate = async (value,{ name }) => {
    console.log(value,name);

    const params = {
        cartid:CartList.value[name].id,
        nums:value,
        busid:business.value.id
    }

    const result = await proxy.$http.post('/cart/edit',params);

    if(result.code === 1)
    {
        CartList.value[name].total = (parseFloat(CartList.value[name].price) * value).toFixed(2);
    }else{
        proxy.$fail(result.msg);
    }
}

const total = computed(() =>
{
    let total = 0;

    if(CheckedArr.value.length > 0)
    {
        for(let item of CartList.value)
        {
            if(CheckedArr.value.includes(item.id))
            {
                total += parseFloat(item.total);
            }
        }
    }

    return total * 100;
});

const OnDel = (item,index) =>
{
    proxy.$confirm({
        title:'删除',
        message:'是否确认删除购物车商品？'
    }).then(async () =>
    {
        const params = {
            cartid:item.id,
            busid:business.value.id
        }

        const result = await proxy.$http.post('/cart/del',params);

        if(result.code === 1)
        {
            proxy.$success(result.msg,() => CartList.value.splice(index,1));
        }else{
            proxy.$fail(result.msg);
        }
    }).catch(err => {});
}

const ToProductInfo = (proid) => proxy.$router.push({path:'/product/info',query:{proid}})

const OnBack = () => action.value == 'info' ? proxy.$router.back() : proxy.$router.push('/');
</script>

<style scoped>
@import url('/assets/css/cart.css');
</style>